<template >
  <div>
    <!-- search -->
    <div class="search  ">
      <el-row>
        <el-col :span="18">
          <el-form>


            <div class="block">
              <span class="demonstration">根据创建日期搜索</span>
              <el-date-picker v-model="firstkw" type="datetime" placeholder="创建日期">
              </el-date-picker>
              <el-date-picker v-model="endkw" type="datetime" placeholder="结束日期">
              </el-date-picker>
            </div>


          </el-form>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
          <el-button type="primary" @click="do_add()">添加</el-button>
          <el-button type="primary" @click="shanchu()">一键删除</el-button>
        </el-col>
      </el-row>

    </div>
    <!-- 添加 -->
    <el-dialog :title="dialog.title" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="form" :model="form">
        <el-form-item label="收支类型">
          <el-select v-model="form.type" placeholder="收支类型">
            <el-option label="微信" value="微信">微信</el-option>
            <el-option label="现金" value="现金">现金</el-option>
            <el-option label="信用卡" value="信用卡">信用卡</el-option>
            <el-option label="支付宝" value="支付宝">支付宝</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收支描述" prop="describe">
          <el-input v-model="form.describe"></el-input>
        </el-form-item>
        <el-form-item label="收入" prop="income">
          <el-input v-model="form.income"></el-input>
        </el-form-item>
        <el-form-item label="支出" prop="expend">
          <el-input v-model="form.expend"></el-input>
        </el-form-item>
        <el-form-item label="账户现金">
          <el-input v-model="form.cash"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="form.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" v-if="dialog.type =='add'" @click="add">确 定</el-button>
        <el-button type="primary" @click="update()" v-else>修 改</el-button>
      </div>
    </el-dialog>
    <!-- 列表 -->
    <template>
      <el-table :data="filterlist" border style="width: 100%">
        <el-table-column align="center" type="index" label="序号">
        </el-table-column>
        <el-table-column align="center" prop="date" label="创建时间">
          <template slot-scope="scope"> <span>{{scope.row.date | formatTime}}</span> </template>
        </el-table-column>
        <el-table-column align="center" prop="type" label="收支类型">
        </el-table-column>
        <el-table-column align="center" prop="describe" label="收支描述">
        </el-table-column>
        <el-table-column align="center" prop="income" label="收入" style="color: yellowgreen">
        </el-table-column>
        <el-table-column align="center" prop="expend" label="支出" color=" red">
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="warning" size="mini" @click="do_update(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" @click="del(scope.row._id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
      :page-sizes="[2,3,5,10]" :page-size="pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>
  </div>
</template>
<script>
export default {
  data() {
    return {
      dialog: {
        title: '添加',
        type: "add",
      },
      list: [],
      filterlist: [],
      token: "",
      date: '',
      dialogFormVisible: false,
      dialogFormVisible1: false,
      // 添加数据
      form: {
        type: "",
        describe: "",
        income: "",
        expend: "",
        cash: "",
        remark: "",
      },
      id: '',

      //搜索 
      firstkw: "",
      endkw: "",
      // 分页
      page: 1,
      pagesize: 5,
      total: 0,
      rules: {
        describe: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        income: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ],
        expend: [
          { required: true, message: '不能为空', trigger: 'blur' },
        ]

      }
    };

  },
  created() {
    /**刷添加的脚本**/
    // this.waigua()

    var kk = localStorage.getItem("token") || "";
    var aa = kk.split(" ");
    this.token = aa[1];
    this.getlist();
  },
  methods: {
    // 获取列表数据
    async getlist() {
      var res = await this.axios({
        url: "/api/profiles",
      });
      console.log(res);
      this.list = res.data;
      this.filterlist = this.list
      this.total = res.data.length

    },
    // 删除
    del(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        var res = await this.axios({
          url: `/api/profiles/delete/${id}`,
          method: "DELETE",
        });
        console.log(res);
        if (res.status == 200) {
          this.filterlist.splice(id,1)

        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 添加
    do_add() {
      this.dialogFormVisible = true
      this.dialog.title = "添加资金管理",
        this.dialog.type = "add"
      this.form = {}

    },
    async add() {
      this.$refs.form.validate(async(valid)=>{
        if(!valid) {
          return this.$message.error("校验失败")
        } else{
          var res = await this.axios({
            url: "/api/profiles/add",
            method: "POST",
            data: this.form,
          });
          console.log(res);
          var obj = res.data;
          console.log(obj);
          this.$message.success('添加成功')
          this.dialogFormVisible = false

      this.getlist();
          this.form.type = '',
          this.form.describe = '',
          this.form.income = '',
          this.form.expend = '',
          this.form.cash = '',
          this.form.remark = ''
        }

      })

    },
    // 编辑
    do_update(row) {
      this.dialog.title = "修改资金管理",
        this.dialog.type = "update"
      this.dialogFormVisible = true;
      console.log(row);
      let id = row._id
      this.form = row
      this.id = id

    },
    async update() {
      let id = this.id
      var res = await this.axios({
        url: `/api/profiles/edit/${id}`,
        method: "POST",
        data: this.form
      });
      console.log(res);
      this.$message.success('编辑成功')
      this.dialogFormVisible = false;
      this.form = {}
      this.getlist()

    },
    // 搜索
    async search() {
      var res = await this.axios({
        url: "/api/profiles",
      });
      console.log(res);
      this.list = res.data;
      let firstkw = this.firstkw.getTime()
      let endkw = this.endkw.getTime()
      console.log(firstkw, endkw);

      this.filterlist = this.list.filter(item => {
        var time = new Date(item.date).getTime()
        return time >= firstkw && time < endkw
      })
    },
    // 外挂添加
    waigua() {
      setInterval(async () => {
        var res = await this.axios({
          url: "/api/profiles/add",
          method: "POST",
          data: {
            type: "微信",
            describe: "给你们写点数据",
            income: "一共你们删除",
            expend: "不用谢",
            cash: "200",
            remark: "基金",
          },
        });
        this.getlist();
      }, 10)
    },
    // 一键删除
    shanchu() {
      this.list.forEach(async (item) => {
        var res = await this.axios({
          url: `/api/profiles/delete/${item._id}`,
          method: "DELETE",
        });
      })
      this.getlist()
    },
    // 分页
    handleSizeChange(val) {
      this.pagesize = val
      var filterlists = this.list.filter((item, index) => {
        let state = (this.page - 1) * val
        let end = val * this.page
        return index >= state && index < end
      })

      this.filterlist = filterlists
    },
    handleCurrentChange(val) {
      this.page = val

      var filterlists = this.list.filter((item, index) => {
        let state = (val - 1) * this.pagesize
        let end = this.pagesize * val
        return index >= state && index < end
      })

      this.filterlist = filterlists

    },
  },
  filters: {
    formatTime(val) {
      let time = new Date(val)
      let year = time.getFullYear()
      let obj = {
        month: time.getMonth() + 1,
        day: time.getDate(),
        hour: time.getHours(),
        minute: time.getMinutes(),
        second: time.getSeconds()
      }
      for (let i in obj) {
        obj[i] = obj[i] < 10 ? "0" + obj[i] : obj[i]
      }
      return `${year}-${obj.month}-${obj.day} ${obj.hour}:${obj.minute}:${obj.second}`
    }
  }
};
</script>
<style >
.search {
  margin: 10px;
}

.el-col-6 {
  width: 300px;
}

.el-picker-panel__body {
  width: 150px;
}

.block {
  width: 800px;
}

.el-form-item__label {
  color: #000;
}
</style>

